﻿using System;
using System.Runtime.CompilerServices;
using System.Threading;

namespace JH
{
    /// <summary>
    /// 条件等待器，满足条件后继续执行
    /// </summary>
    public struct ConditionAwaiter<T> : ICriticalNotifyCompletion
    {
        /// <summary>
        ///  组合非泛型的ConditionAwaiter
        /// </summary>
        private ConditionAwaiter _awaiter;

        /// <summary>
        ///  获取结果的方法
        /// </summary>
        private readonly Func<T> _getResult;

        /// <summary>
        ///  INotifyCompletion接口中的完成判定
        /// </summary>
        public bool IsCompleted => _awaiter.CanInvoke();

        /// <summary>
        /// 初始化或重置方法（从池中取出awaiter时调用）
        /// </summary>
        public ConditionAwaiter(Func<bool> condition, Func<T> getResult, CancellationToken token = default,
            DispatchState dispatchState = DispatchState.Default)
        {
            _awaiter = new ConditionAwaiter(condition, token, dispatchState);
            _getResult = getResult;
        }

        public T GetResult()
        {
            _awaiter.GetResult();
            return _getResult == null ? default : _getResult.Invoke();
        }

        /// <summary>
        ///  设置异常
        /// </summary>
        public void SetException(Exception exception) => _awaiter.SetException(exception);

        public void OnCompleted(Action continuation) => _awaiter.OnCompleted(continuation);
        public void UnsafeOnCompleted(Action continuation) => _awaiter.UnsafeOnCompleted(continuation);
        public ConditionAwaiter<T> GetAwaiter() => this;
    }
}